//服务器地址
import {server} from '../config/index.js';

mui.init();
castapp.init();

mui.plusReady(function(){
	//按手机返回键
	var lastTime = Date.now();
	mui.back = function(){
		var now = Date.now();
		if(now - lastTime <500){ //两次时间间隔不超过500毫秒
			plus.runtime.quit();
		}else{
			castapp.prompt('再按一次退出程序');
			lastTime = now;
		}
	}
});


var $inputEles = $('input');


//点击注册
$('p.login-a a.register').get(0).addEventListener('tap',function(e){
	e.preventDefault();
	castapp.newInterface({
		url: './register.html',
		id: 'html/register'
	});
});

//点击忘记密码
$('p.login-a a.forget').get(0).addEventListener('tap',function(e){
	e.preventDefault();
	castapp.newInterface({
		url: './reset_password.html',
		id: 'html/reset_password'
	});
});

//点击登录
$('.login-btn button').get(0).addEventListener('tap',function(e){
	e.preventDefault();
	var username = $inputEles.eq(0).val().trim();  //用户名
	var password = $inputEles.eq(1).val().trim();  //密码
	
	if(!username || !password){
		castapp.prompt('用户名或密码不能为空');
		return;
	}
	
	if(/[.\(\)<>\/\\?@#]/.test(username)){
		castapp.prompt('不能带特殊字符');
		return;
	}
	if(username.length>12){
		castapp.prompt('用户名长度为1~12');
		return;
	}
	
	//请求登录
	$.ajax({
		url: server + '/api/user/login',
		type: 'post',
		data: {
			nickname: username,
			password: password
		},
		success:function(res){
			if(res.msg == 'OK'){
				var data = res.data;
				castapp.prompt('登录成功');
				var origin_userInfo = localStorage.getItem('userInfo');
				origin_userInfo = origin_userInfo? JSON.parse(origin_userInfo): {};
				
				var userInfo = {
					nickname: username, //昵称  
					BB_num: data.uuid,  //BB号
					telephone: data.telephoto? data.telephoto: null,  //电话
					avator: data.avatar? data.avatar: null,   //头像
					qrcode: origin_userInfo.nickname==username? origin_userInfo.qrcode: null,    //二维码
				}
				localStorage.setItem('userInfo',JSON.stringify(userInfo));
				setTimeout(function(){
					castapp.newInterface({
						url: '../nav.html',
						id: 'nav'
					});
					castapp.closeCurrentInterface();
				},500);
				
			}else if(res.msg=='NO'){
				castapp.prompt('用户名不存在');
			}else if(res.msg=='Err'){
				castapp.prompt('用户或密码错误');
			}
		},
		error: function(err){
			castapp.prompt('服务错误,请重试');
		}
	});
	
	
});